//
//  LocationManager.m
//  SuYue
//
//  Created by Win10 on 2018/11/23.
//  Copyright © 2018 Win10. All rights reserved.
//

#import "LocationManager.h"
#import "SystemDeviceTool.h"
#import "ZJPhoneIPAddress.h"
@interface LocationManager()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager * locationManager;
@end
@implementation LocationManager

+ (instancetype)sharedInstance{
    static LocationManager *shared;
    static dispatch_once_t onceAction;
    dispatch_once(&onceAction, ^{
        shared =  [[[self class]alloc]init];
    });
    return shared;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        // 设置代理
        _locationManager.delegate = self;
        // 设置定位精确度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        // 取得定位权限，有两个方法，取决于你的定位使用情况
        // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
        // 这句话ios8以上版本使用。
        [_locationManager requestWhenInUseAuthorization];
        // 开始定位
        [_locationManager startUpdatingLocation];
        [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(updateLocation) userInfo:nil repeats:NO];
//        self.isUpdating = NO;
    }
    return self;
}

//locationManager:didUpdateLocations:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations
{
    self.currentLocation = locations.firstObject;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    debugLog(@"%@",error);
}

- (void)updateLocation{
//    if ([[NSDate date] timeIntervalSince1970] > self.nextTime) {
        // 获取当前所在的城市名
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //根据经纬度反向地理编译出地址信息
        self.isUpdating = YES;
        [geocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *array, NSError *error){
            self.isUpdating = NO;
            if (array.count > 0){
                CLPlacemark *placemark = [array objectAtIndex:0];
                //获取当前城市
                NSString *city = placemark.locality;
                if (!city) {
                    //注意：四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                // 位置名
                NSLog(@"name,%@",placemark.name);
                // 街道
                NSLog(@"thoroughfare,%@",placemark.thoroughfare);
                // 子街道
                NSLog(@"subThoroughfare,%@",placemark.subThoroughfare);
                // 市
                NSLog(@"locality,%@",placemark.locality);
                // 区
                NSLog(@"subLocality,%@",placemark.subLocality);
                debugLog(@"%@",city);
                NSMutableDictionary * param = [NSMutableDictionary dictionary];
                param[@"macId"] = [SystemDeviceTool getUUID];
                param[@"ipAddr"] = [[ZJPhoneIPAddress new] getIPAddress];
                param[@"latitude"] = @(self.currentLocation.coordinate.latitude);
                param[@"longitude"] = @(self.currentLocation.coordinate.longitude);
                param[@"address"] = [NSString stringWithFormat:@"%@%@%@%@",city,placemark.subLocality,placemark.thoroughfare,placemark.subThoroughfare];
//                [param setObject:city forKey:@"city"];
//                [param setObject:@(self.currentLocation.timestamp.timeIntervalSince1970) forKey:@"time"];
                self.isUpdating = YES;
                [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_upload_location) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error){
                    self.isUpdating = NO;
                    if (!error) {
//                        self.nextTime = [[NSDate date] timeIntervalSince1970] + (60*10);
                        NSLog(@"地理位置上传成功");
                    }
                }];
            }else if (error == nil && [array count] == 0) {
                NSLog(@"没有结果返回.");
            }else if (error != nil)  {
                //NSLog(@"An error occurred = %@", error);
            }
        }];
//    }
}
@end
